package net.xuwu.marry.common.struts;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.xuwu.marry.common.constant.GlobinConstant;

import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class MarryStrutsInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		
		HttpServletRequest request = (HttpServletRequest) arg0.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) arg0.getInvocationContext().get(StrutsStatics.HTTP_RESPONSE);
		String userName = (String) arg0.getInvocationContext().getSession().get(GlobinConstant.SESSION_KEY);
		
		InputStream is = request.getInputStream();
		//接收前台的json参数
		String jsonData = this.getStrFromInputsteam(is);
		//字符转码
		jsonData = new String(jsonData.getBytes("iso-8859-1"),"utf-8");
		
		//接收到的参数放到request中便struts里面接收
		request.setAttribute(GlobinConstant.RECEIVE_JSON_DATA, jsonData);
		//时间 
		long start = System.currentTimeMillis();
		//运行
		String resultData = arg0.invoke();
		//ִ结束时间
		long end  = System.currentTimeMillis();
		
		System.out.println(arg0.getAction().getClass().getName()+"=============="+(end-start)+"ms");
		
		System.out.println("return=="+resultData);
		
		String result = (String) request.getAttribute(GlobinConstant.SEND_JSON_DATA);
		
		System.out.println("数据为==="+result);
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		this.writeResponseInfo(out, result);
		
		return resultData;
	}
	
	/**
	 * ���������еõ��ַ�
	 * @return
	 * @throws IOException 
	 */
	private String getStrFromInputsteam(InputStream is) throws IOException{
		
		StringBuilder sb = new StringBuilder();
		int i=0;
		
		while((i=is.read())!=-1){
			sb.append((char)i);
		}
		return sb.toString();
	}
	
	/**
	 *��װ�����Ϣ 
	 */
	private void writeResponseInfo(PrintWriter pw,String returnData){
		
		pw.write(returnData);
		pw.flush();
		pw.close();
		
	}

}
